<?php

namespace app\admin\controller;

use think\Db;
use think\Cache;
use app\api\model\Juhe;
use app\api\model\ConfigSystem as Config;
use app\service\UserIntimate;

class Tool extends Common
{
    public function sms()
    {
        if (request()->isAjax()) {
            $phone = input('phone');
            if(!$phone){
                return ['err'=>'请输入手机号'];
            }
            $phone = explode(',', $phone);
            $mbid = input('mbid');

            $juhe = new Juhe();
            $num = 0;
            foreach ($phone as $item) {
                if(!preg_match("/^1[3456789]\d{9}$/", $item)){
                    continue;
                }
                try {
                    $juhe->sendTpl($item, $mbid);
                    $num++;
                } catch (Exception $e) {
                    
                }
            }
            if($num){
                return ['ret'=>'本次成功发送 ' . $num . ' 条消息'];
            }
            return ['err'=>'发送失败'];
        }else{
            return $this->fetch();
        }
    }
    public function UserIntimateCount($userid = 0, $touserid = 0)
    {
        if (request()->isAjax()) {
            $couple = input('couple/s', '');
            if ($couple) {
                $couple = explode(',', $couple);
                if (sizeof($couple) == 2) {
                    $userid = intval($couple[0]);
                    $touserid = intval($couple[1]);
                }
            }
            $result = UserIntimate::Count($userid, $touserid);
            $result = $result ?: 0;
            return ['ret'=>$result];
        }else{
            return $this->fetch();
        }
    }
    public function UserTopupCount($userid = 0)
    {
        if (request()->isAjax()) {
            $result = UserIntimate::TopupCount($userid);
            $result['topup'] = round($result['topup'], 2);
            return ['ret'=>$result ?? 0];
        }else{
            return $this->fetch();
        }
    }



    public function createuser($masterimg = '', $sex = '女')
    {
        if (request()->isAjax()) {
            $masterimg = explode(',', $masterimg);
            $num = 0;
            foreach ($masterimg as $key => $value) {
                try {
                    action('api/tpl/createuser', ['userinfo'=>['a'=>$value, 'sex'=>$sex, 'r'=>2]]);
                    $num++;
                } catch (\Exception $e) {
                    
                }
            }
            return ['ret'=> '本次预估生成 ' .  $num . ' 个虚拟用户'];
        }else{
            return $this->fetch();
        }
    }

    public function chatPayer($userid = 0, $touserid = 0)
    {
        if (request()->isAjax()) {
            $userinfo = Db::name('user')->find($userid);
            $touserinfo = Db::name('user')->find($touserid);
            $payer_id = $userinfo['sex']=='男'?$userinfo['id']:$touserinfo['id'];
            $configTwoWayCharge = Config::index('two_way_charge');
            if ($configTwoWayCharge['two_way_charge_status'] == 1 && ((strtotime($userinfo['register_datetime']) > strtotime($configTwoWayCharge['two_way_charge_reg_time'])) || (strtotime($touserinfo['register_datetime']) > strtotime($configTwoWayCharge['two_way_charge_reg_time'])))) {
                $ChatChargeRecordMap = $userinfo['id'] < $touserinfo['id'] ? [
                    'user_id' => $userinfo['id'],
                    'another_id' => $touserinfo['id'],
                ] :  [
                    'user_id' => $touserinfo['id'],
                    'another_id' => $userinfo['id'],
                ];
                $ChatChargeRecords = Db::name('chat_charge_records')->master(true)->where($ChatChargeRecordMap)->find();
                if ($ChatChargeRecords && $ChatChargeRecords['payer']) {
                    $payer_id = $touserinfo['id'] == $ChatChargeRecords['payer'] ? $touserinfo['id'] : $userinfo['id'];
                }
            }
            return ['ret'=>$payer_id];
        }else{
            return $this->fetch();
        }
    }


    public function getIpUser()
    {
        $ips = input('search_name', '');
        $ips = $ips ? explode(',', $ips) : [];
        $repeats = [];
        if ($ips) {
            $where = [];
            foreach ($ips as $key => $value) {
                $where[] = "ips like '$value%' or ips like '%,$value%'";
            }
            $repeats = Db::name('user_repeat_check')->where(implode(' or ', $where))->field('user_id,ips')->limit(1000)->select();
            $users = Db::name('user')->where(['id'=>['in', array_column($repeats, 'user_id')]])->column('id,name,sex,age,phone,city,volley,score,shouyi,register_datetime,last_login_datetime,is_banned,banned_desc,banned_end_time,entertainment','id');
            foreach ($repeats as &$value) {
                $ip = explode(',', $value['ips']);
                foreach ($ips as $sk => $sv) {
                    foreach ($ip as $v) {
                        if (strpos($v, $sv) === 0) $value['ip'][] = $v;
                    }
                }
                $value['user'] = $users[$value['user_id']] ?? false;
                unset($value['ips']);
            }
            // echo "<pre>";
            // print_r($repeats);
        }
        $this->assign('data', $repeats);
        return $this->fetch();
    }

    public function consumption1()
    {
        $filter = Db::name('limit_dating')->column('user_id');
        if (request()->isAjax()) {

            $topup = input('topup/d', 3000);
            $rate = input('rate/d', 50);

            $rechargeUser = Db::name('user_data')->master()->where(['topup'=>['>', $topup / 10]])->column('user_id');
            $users = Db::name('user')
                ->master()
                ->where(['id'=>['in', $rechargeUser], 'sex'=>'男', 'is_banned'=>0, 'delete_time'=>0])
                ->where(['id'=>['not in', $filter]])
                ->whereTime('last_login_datetime', '-30 day')
                // ->page(1)
                // ->limit(10)
                ->column('id');
            $uids = [];
            foreach ($users as $key => $value) {
                $result = UserIntimate::TopupCount2($value);
                if ($result['topup'] >= $topup) {
                    $result['user_intimate'] = Db::name('user_intimate')->master()->where("find_in_set($value, couple_a)")->field('couple_a,intimate')->select();
                    $uids[$result['user_id']] = $result;
                }
            }

            $items = [];
            foreach ($uids as $key => $value) {
                foreach ($value['user_intimate'] as $k => $v) {
                    $r = ($v['intimate'] / 5) / $value['topup'] * 100;
                    if ($r > $rate) {
                        $v['topup'] = $value['topup'];
                        $v['user_id'] = $value['user_id'];
                        $v['rate'] = $r;
                        $v['user_ids'] = $value['userids'];
                        $items[] = $v;
                    }
                }
            }

            Db::name('tongji_user_intimate')->where(['id'=>['>', 0]])->limit(20000)->delete();
            Db::name('tongji_user_intimate')->insertAll($items);
            // echo "<pre>";
            // var_dump($items);
            return ['state'=>1, 'msg'=>'检索完成'];
        }else{
            $where = [];
            $name = input('name/d',0);
            if ($name) {
                $where['user_id'] = $name;
            }

            $data=DB::name('tongji_user_intimate')->master()->where(['user_id'=>['not in', $filter]])->where($where)->order('id desc')->paginate(_getCachePages(),false,['query'=>request()->param()])->each(function($item, $key){
                $user = explode(',', $item['couple_a']);
                $item['touser'] = $user[0] == $item['user_id'] ? $user[1] : $user[0];
                return $item;
            });
            $this->assign('data',$data);
            $page = $data->render();
            $this->assign('page', $page);
            return $this->fetch();
        }
    }


    public function consumption2()
    {
        $filter = Db::name('limit_dating')->column('user_id');
        if (request()->isAjax()) {
            set_time_limit(30);

            $topup = input('topup/d');
            $rate = input('rate/d');
            $search = input('search/d', 3);

            if (!$topup || $topup < 1000) return ['state'=>0, 'msg'=>'金额不得低于1000'];
            if (!$rate || $rate < 10) return ['state'=>0, 'msg'=>'比例不得低于10%'];

            $lasttime = ['-30 day', '-90 day', '-180 day', '-100 year'];

            $rechargeUser = Db::name('user_data')->master()->where(['topup'=>['>=', $topup / 2]])->column('topup','user_id');
            $users = Db::name('user')
                ->master()
                ->where(['id'=>['in', array_keys($rechargeUser)], 'sex'=>'男', 'is_banned'=>0, 'delete_time'=>0])
                ->where(['id'=>['not in', $filter]])
                ->whereTime('last_login_datetime', $lasttime[$search])
                ->column('id');
            $uids = [];
            $where = [];
            foreach ($users as $key => $value) {
                $uids[$value]['topup'] = $rechargeUser[$value];
                $where[] = "find_in_set($value, couple_a)";
                $uids[$value]['user_intimate'] = [];
            }

            $user_intimate = Db::name('user_intimate')->master()->where(['intimate'=>['>=', $topup * 5 * $rate / 100]])->where(implode(' or ', $where))->field('couple_a,intimate')->fetchSql(false)->select();
            foreach ($user_intimate as $key => $value) {
                $uid = explode(',', $value['couple_a']);
                if (in_array($uid[0], $users)) {
                    $uids[$uid[0]]['user_intimate'][] = $value;
                } else {
                    $uids[$uid[1]]['user_intimate'][] = $value;
                }
            }

            $items = [];
            foreach ($uids as $key => $value) {
                foreach ($value['user_intimate'] as $k => $v) {
                    $r = ($v['intimate'] / 5) / $value['topup'] * 100;
                    if ($r >= $rate) {
                        $result = UserIntimate::TopupCount2($key);
                        $r = ($v['intimate'] / 5) / $result['topup'] * 100;
                        if ($result['topup'] >= $topup && $r >= $rate) {
                            $v['topup'] = $result['topup'];
                            $v['user_id'] = $key;
                            $v['rate'] = $r;
                            $v['user_ids'] = $result['userids']??'';
                            $items[] = $v;
                        }
                    }
                }
            }

            Db::name('tongji_user_intimate')->where(['id'=>['>', 0]])->limit(20000)->delete();
            Db::name('tongji_user_intimate')->insertAll($items);
            // echo "<pre>";
            // var_dump($items);
            return ['state'=>1, 'msg'=>'检索完成'];
        }else{
            $where = [];
            $name = input('name/d',0);
            if ($name) {
                $where['user_id'] = $name;
            }

            $data=DB::name('tongji_user_intimate')->master()->where(['user_id'=>['not in', $filter]])->where($where)->order('id desc')->paginate(_getCachePages(),false,['query'=>request()->param()])->each(function($item, $key){
                $user = explode(',', $item['couple_a']);
                $item['touser'] = $user[0] == $item['user_id'] ? $user[1] : $user[0];
                $item['user_ids'] = implode(',', array_diff(explode(',', $item['user_ids']), [$item['user_id']]));
                return $item;
            });
            $this->assign('data',$data);
            $page = $data->render();
            $this->assign('page', $page);
            return $this->fetch();
        }
    }
    public function consumption()
    {
        $filter = Db::name('limit_dating')->column('user_id');
        if (request()->isAjax()) {
            set_time_limit(30);

            $topup = input('topup/d');
            $rate = input('rate/d');
            $search = input('search/d', 3);

            if (!$topup || $topup < 3000) return ['state'=>0, 'msg'=>'金额不得低于3000'];
            if (!$rate || $rate < 30) return ['state'=>0, 'msg'=>'比例不得低于30%'];

            $lasttime = ['-30 day', '-90 day', '-180 day', '-100 year'];

            $rechargeUser = Db::name('user_data')->master()->where(['topup'=>['>=', $topup]])->column('topup','user_id');
            $users = Db::name('user')
                ->master()
                ->where(['id'=>['in', array_keys($rechargeUser)], 'sex'=>'男', 'is_banned'=>0, 'delete_time'=>0])
                ->where(['id'=>['not in', $filter]])
                ->whereTime('last_login_datetime', $lasttime[$search])
                ->column('id');
            $uids = [];
            $where = [];
            foreach ($users as $key => $value) {
                $uids[$value]['topup'] = $rechargeUser[$value];
                $where[] = "find_in_set($value, couple_a)";
                $uids[$value]['user_intimate'] = [];
            }

            $user_intimate = Db::name('user_intimate')->master()->where(['intimate'=>['>=', $topup * 5 * $rate / 100]])->where(implode(' or ', $where))->field('couple_a,intimate')->fetchSql(false)->select();
            foreach ($user_intimate as $key => $value) {
                $uid = explode(',', $value['couple_a']);
                if (in_array($uid[0], $users)) {
                    $uids[$uid[0]]['user_intimate'][] = $value;
                } else {
                    $uids[$uid[1]]['user_intimate'][] = $value;
                }
            }

            $items = [];
            foreach ($uids as $key => $value) {
                foreach ($value['user_intimate'] as $k => $v) {
                    $r = ($v['intimate'] / 5) / $value['topup'] * 100;
                    if ($r >= $rate) {
                        $v['topup'] = $value['topup'];
                        $v['user_id'] = $key;
                        $v['rate'] = $r;
                        $items[] = $v;
                    }
                }
            }

            Db::name('tongji_user_intimate')->where(['id'=>['>', 0]])->limit(20000)->delete();
            Db::name('tongji_user_intimate')->insertAll($items);
            // echo "<pre>";
            // var_dump($items);
            return ['state'=>1, 'msg'=>'检索完成'];
        }else{
            $where = [];
            $name = input('name/d',0);
            if ($name) {
                $where['user_id'] = $name;
            }

            $data=DB::name('tongji_user_intimate')->master()->where(['user_id'=>['not in', $filter]])->where($where)->order('id desc')->paginate(_getCachePages(),false,['query'=>request()->param()])->each(function($item, $key){
                $user = explode(',', $item['couple_a']);
                $item['touser'] = $user[0] == $item['user_id'] ? $user[1] : $user[0];
                return $item;
            });
            $dataList = $data->all();
            $users = Db::name('user')
                ->where(['id'=>['in', array_merge(array_column($dataList, 'user_id'), array_column($dataList, 'touser'))]])
                ->column('last_login_datetime', 'id');
            foreach ($dataList as &$value) {
                $value['last_login_datetime'] = $users[$value['user_id']]??'';
                $value['touser_last_login_datetime'] = $users[$value['touser']]??'';
            }
            $this->assign('data',$dataList);
            $page = $data->render();
            $this->assign('page', $page);
            return $this->fetch();
        }
    }

    public function scriptCheck($refresh = false)
    {
        $cachekey = 'scriptCheck';

        $alluids = Cache::store('redisUnclear')->get($cachekey);
        if (!$alluids || $refresh) {
            $where = ['delete_time'=>0,'sex'=>'女', 'quality'=>['<>', 1]];
            
            $uids = Db::name('user')
                ->where($where)
                ->whereTime('last_login_datetime', '-1 day')
                ->column('id');

            // 查询并拼接同一个用户的 accessibility
            $accessibility = Db::name('user_device_accessibility')
                ->field("user_id, GROUP_CONCAT(accessibility SEPARATOR '---') as accessibility")
                ->where(['user_id' => ['in', $uids], 'accessibility' => ['not like', '-1%']])
                ->group('user_id')
                ->select();

            // 将结果转换为关联数组
            $accessibilityresult = [];
            foreach ($accessibility as $row) {
                $accessibilityresult[$row['user_id']] = $row['accessibility'];
            }

            $kefu = Db::name('config_system')->where(['title'=>'id'])->value('content');
            $userids = Db::name('privatechat')
                ->where(['userid'=>['in', array_keys($accessibilityresult)], 'touserid'=>['<>', $kefu]])
                ->where("(front_id!='' and type not in (9,10)) or (front_id='' and type in (9,10))")
                ->whereTime('addtime', '-1 day')
                ->group('userid')
                ->column('count(*)','userid');

            $alluids = [];
            foreach ($userids as $key => $value) {
                if ($value>10) {
                    $alluids[] = $key;
                }
            }
            Cache::store('redisUnclear')->set($cachekey, $alluids);
        } else {
            // 查询并拼接同一个用户的 accessibility
            $accessibility = Db::name('user_device_accessibility')
                ->field("user_id, GROUP_CONCAT(accessibility SEPARATOR '---') as accessibility")
                ->where(['user_id' => ['in', $alluids], 'accessibility' => ['not like', '-1%']])
                ->group('user_id')
                ->select();

            // 将结果转换为关联数组
            $accessibilityresult = [];
            foreach ($accessibility as $row) {
                $accessibilityresult[$row['user_id']] = $row['accessibility'];
            }
        }


        $where = ['id'=>['in', $alluids]];
        $search_name = input('search_name/s','');
        if ($search_name) {
            if (in_array($search_name, $alluids)) {
                $where['id'] = $search_name;
            } else {
                $where['id'] = 0;
            }
        }
        $data = Db::name('user')->where($where)->order('id desc')->paginate(_getCachePages(),false,['query'=>request()->param()]);

        $dataList = $data->all();
        foreach ($dataList as &$value) {
            $value['accessibility'] = $accessibilityresult[$value['id']] ?? '';
        }

        $page = $data->render();
        $this->assign('data', $dataList);
        $this->assign('page', $page);
        $this->assign('url', $cachekey);
        
        return $this->fetch();
    }
    /*
    2024-11-11
    脚本检测2
     */
    public function scriptCheck2($refresh = false)
    {
        $cachekey = 'scriptCheck2';

        $alluids = Cache::store('redisUnclear')->get($cachekey);
        if (!$alluids || $refresh) {
            $where = ['delete_time'=>0,'sex'=>'女'];
            
            $uids = Db::name('user')
                ->where($where)
                ->whereTime('last_login_datetime', '-1 day')
                ->column('id');

            // 查询并拼接同一个用户的 accessibility
            $accessibility = Db::name('user_device_accessibility')
                ->field("user_id, GROUP_CONCAT(accessibility SEPARATOR '---') as accessibility")
                ->where(['user_id' => ['in', $uids]])
                ->group('user_id')
                ->select();

            // 将结果转换为关联数组
            $accessibilityresult = [];
            foreach ($accessibility as $row) {
                $accessibilityresult[$row['user_id']] = $row['accessibility'];
            }

            $kefu = Db::name('config_system')->where(['title'=>'id'])->value('content');
            $userids = Db::name('privatechat')
                ->where(['userid'=>['in', array_keys($accessibilityresult)], 'touserid'=>['<>', $kefu]])
                ->where("(front_id!='' and type not in (9,10)) or (front_id='' and type in (9,10))")
                ->whereTime('addtime', '-1 day')
                ->group('userid')
                ->column('count(*)','userid');

            $alluids = [];
            foreach ($userids as $key => $value) {
                if ($value>10) {
                    $alluids[] = $key;
                }
            }
            Cache::store('redisUnclear')->set($cachekey, $alluids);
        } else {
            // 查询并拼接同一个用户的 accessibility
            $accessibility = Db::name('user_device_accessibility')
                ->field("user_id, GROUP_CONCAT(accessibility SEPARATOR '---') as accessibility")
                ->where(['user_id' => ['in', $alluids]])
                ->group('user_id')
                ->select();

            // 将结果转换为关联数组
            $accessibilityresult = [];
            foreach ($accessibility as $row) {
                $accessibilityresult[$row['user_id']] = $row['accessibility'];
            }
        }


        $where = ['id'=>['in', $alluids]];
        $search_name = input('search_name/s','');
        if ($search_name) {
            if (in_array($search_name, $alluids)) {
                $where['id'] = $search_name;
            } else {
                $where['id'] = 0;
            }
        }
        $data = Db::name('user')->where($where)->order('id desc')->paginate(_getCachePages(),false,['query'=>request()->param()]);

        $dataList = $data->all();
        foreach ($dataList as &$value) {
            $value['accessibility'] = $accessibilityresult[$value['id']] ?? '';
        }

        $page = $data->render();
        $this->assign('data', $dataList);
        $this->assign('page', $page);
        $this->assign('url', $cachekey);
        
        return $this->fetch('script_check');
    }

}
